const request = require('request');
const token = require('../utils/getToken');
const express = require('express');
const router = express.Router();

router.all('/', (req, res, next) =>{
    if (req.method != 'GET' && req.method != 'POST') {
        res.json({
            code: 404,
            msg: "This method isn't allowed",
        });
    }else{
        let queryData = null;
        if (req.method == 'GET') {
            queryData = req.query;
        }else if (req.method == 'POST') {
            queryData = req.body;
        }
        if (!('scene' in queryData) || !('page' in queryData)) {
            res.json({
                code: 404,
                msg: "请求参数sence或page为空",
            });
        }else{
            token.AccessToken().then(ret => {
                let AccessToken = ret;
                request({
                    url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${AccessToken}`,
                    method: 'POST',
                    encoding: null,
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify(queryData),
                }, (err, response, body) =>{
                    
                    if (err) throw err;
                    if (response.statusCode != 200) {
                        res.json({
                            code: 405,
                            msg: "网络错误"
                        })
                    }else{
                        if (Buffer.isBuffer(body)) {
                            let imgBase64 = 'data:image/jpeg;base64,' + body.toString('base64');
                            // 二者自行取舍
                            res.json({
                                code: 0,
                                base: imgBase64,
                            });
                        }else{
                            res.json({
                                code: 404,
                                msg: "文件类型错误"
                            })
                        }
                    }
                })
            })
        }
    }
})

module.exports = router;